﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsLive.Id.Client;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Xml;
using OpenContactsNet;
using Microsoft.LiveFX.Client;
using System.Collections.ObjectModel;
using Microsoft.LiveFX.ResourceModel;
using WindowsLiveID;
using Bitter.Win.Services.Twitter;
using Bitter.Win.Services.Flickr;
using Bitter.Win.Services.Facebook;
using Bitter.Win.Services.Live;

namespace Bitter.Win
{
    public partial class MainForm : Form
    {
        private string currentUserName;

        public MainForm()
        {
            InitializeComponent();

            //WindowsLive.Instance.Initialize();

            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
        }

        private LiveOperatingEnvironment env;

        public static ObservableCollection<MeshObject> GetAllMeshFolders(LiveOperatingEnvironment env)
        {
            if (!env.Mesh.MeshObjects.IsLoaded)
                env.Mesh.MeshObjects.Load();

            ObservableCollection<MeshObject> listAllMeshFolders = new ObservableCollection<MeshObject>();


            var meshObjects = from i in env.Mesh.CreateQuery<MeshObject>()
                              where i.Resource.Type == "LiveMeshFolder"
                              select i;

            foreach (MeshObject meshObject in meshObjects)
            {
                listAllMeshFolders.Add(meshObject);
            }
            return listAllMeshFolders;
        }

        string LivefxURL = "https://user-ctp.windows.net/";

        LiveOperatingEnvironment ConnectToLOE(string serverUri, string userId, string password)
        {
            string token = new NetworkCredential(userId, password, serverUri).GetWindowsLiveAuthenticationToken();
            //token = WindowsLive.Instance.Identity.ExportAuthString();

            Uri uri = new Uri(serverUri);

            LiveItemAccessOptions accessOptions = new LiveItemAccessOptions(true);

            LiveOperatingEnvironment env = new LiveOperatingEnvironment();
            env.Connect(token, AuthenticationTokenType.UserToken, uri, accessOptions);

            return env;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            env = ConnectToLOE(LivefxURL, "pixelworld@hotmail.com", "");

            int i = 0;

            foreach (var c in env.Contacts.Entries)
            {
                i++;
                Console.WriteLine(i + " : " + c.Resource.FormattedName);
            }
             //.Take(_environment.Contacts.Entries.Count())

            Console.WriteLine(i.ToString());

            ObservableCollection<MeshObject> meshObjectList = new ObservableCollection<MeshObject>();
            meshObjectList = GetAllMeshFolders(env);
            foreach (MeshObject mo in meshObjectList)
            {
                Console.WriteLine(mo.Resource.Title);
            }

            //string ticket = identity.GetTicket("http://live.com", "MBI", false);

            // Create HTTP request object.

            //bool bSuccess = true;

            //UriBuilder uriBuilder = new UriBuilder();
            //uriBuilder.Scheme = "HTTPS";
            //uriBuilder.Path = "/" + WindowsLive.Instance.Identity.UserName + "/LiveContacts/Contacts";
            //uriBuilder.Host = "livecontacts.services.live.com";
            //uriBuilder.Port = 443;

            //string uriPath = uriBuilder.Uri.AbsoluteUri;
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriPath);
            //request.ContentType = "application/xml; charset=utf-8";
            //request.Method = "GET";

            ////string ticketText = WindowsLive.Instance.Identity.GetTicket("http://livecontacts.services.live.com", false);
            ////XmlDocument ticketXml = new XmlDocument();
            ////ticketXml.LoadXml(ticketText);
            ////string ticket = ticketXml.DocumentElement["CipherData"].ChildNodes[0].InnerText;

            ////ticket = WindowsLive.Instance.Identity.ExportAuthString();

            //request.Headers.Add("Authorization", "WLID1.0 t=\"" + ticket + "=\"");
            ////request.Headers.Add("Authorization", "WLID1.0 t=\"t=" + oID.ExportAuthString() + "=\"");
            //HttpWebResponse resp = null;

            //try
            //{
            //    resp = (HttpWebResponse)request.GetResponse();
            //} 
            //catch(WebException ex) 
            //{

            //}

            //StreamReader reader = new StreamReader(resp.GetResponseStream());
            //string response = reader.ReadToEnd();
        }

        private void SignIn_Click(object sender, EventArgs e)
        {
            WindowsLiveID.Logon logon = new Logon();
            DialogResult result = logon.ShowDialog();

            if (result == DialogResult.OK)
            {
                //MessageBox.Show("You are now signed into the Live Operating Environment.");
            }

            UpdateDisplay();
        }

        private void UpdateDisplay()
        {
            if (WindowsLive.Instance.IsAuthenticated)
            {
                SignIn.Visible = false;
                SignedIn.Visible = true;
                SignedIn.Text = WindowsLive.Instance.PersistedAddress;
            }
            else
            {
                SignIn.Visible = true;
                SignedIn.Visible = false;
            }
        }

        private void SignOut_Click(object sender, EventArgs e)
        {
            WindowsLive.Instance.SignOut();
            UpdateDisplay();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (WindowsLive.Instance.SignInAutomatically)
            {
                WindowsLive.Instance.TryAutomaticLogon();
                UpdateDisplay();
            }
        }

        private void ViewAccount_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://account.live.com/");
        }

        private void AboutBitter_Click(object sender, EventArgs e)
        {
            About frm = new About();
            frm.ShowDialog();
        }

        private string FormatEmails(List<ContactEmail> emails)
        {
            StringBuilder str = new StringBuilder();

            foreach (var email in emails)
            {
                str.Append(email.Value + ", ");
            }

            return str.ToString();
        }

        private string FormatPhoneNumbers(List<ContactPhone> numbers)
        {
            StringBuilder str = new StringBuilder();

            foreach (var number in numbers)
            {
                str.Append(number.Value + ", ");
            }

            return str.ToString();
        }

        private void Navigate(Control control)
        {
            splitContainer1.Panel2.Controls.Clear();
            
            control.Dock = DockStyle.Fill;

            splitContainer1.Panel2.Controls.Add(control);
        }

        private void NavigationTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            switch (e.Node.FullPath)
            {
                case "Services\\Twitter":
                    Navigate(new TwitterMain());
                    break;
                case "Services\\Facebook":
                    Navigate(new FacebookMain());
                    break;
                case "Services\\Flickr":
                    Navigate(new FlickrMain());
                    break;
                case "Home":
                    Navigate(new Welcome());
                    break;
            }

            if (e.Node.Text == "People")
            {
                ContactList list = new ContactList();

                Navigate(list);

                list.ListView.Items.Clear();

                foreach (var contact in WindowsLive.Instance.Environment.Contacts.Entries)
                {
                    if (!contact.IsLoaded)
                    {
                        contact.Load();
                    }

                    ListViewItem item = new ListViewItem(new[] { contact.Resource.FormattedName, FormatPhoneNumbers(contact.Resource.PhoneNumbers), FormatEmails(contact.Resource.Emails) });
                    item.Tag = contact.Resource.ContactId;
                    item.ImageIndex = 0;

                    list.ListView.Items.Add(item);
                }

                Status.Text = string.Format("{0} contacts.", WindowsLive.Instance.Environment.Contacts.Entries.Count());
            }
        }
    }
}
